<template>
  <div class="custom-detail" v-if="customBaseInfo">
    <div class="custom-box">
      <div class="custom-info-box">
        <Avatar size="large" :avatar="customBaseInfo.clientAvatarUrl" @on-click="previewAvatarUrl" />
        <div class="info-box">
          <div class="title ellipsis" :class="dynamicFontSize(customBaseInfo)">{{ customBaseInfo.remarkName || customBaseInfo.clientName }}</div>
          <div class="info-box-bottom">
            <div class="info-left">
              <p class="nick" v-if="showActionBar && clientMobile" >{{ clientMobile }}</p>
              <p class="nick" v-else-if="customBaseInfo.wxChatNickName" >
                <span>微信昵称：</span>
                <span style="max-width: 100px;" class="ellipsis" >{{customBaseInfo.wxChatNickName}}</span>
                <van-tag color="#405170" class="copy" size="medium" :data-clipboard-text="customBaseInfo.wxChatNickName" @click="copy">复制</van-tag>
              </p>
              <p class="custom-browsed">最近访问：{{customBaseInfo.lastViewTime}}</p>
            </div>
            <div class="info-right" v-if="!showActionBar">
              <p class="precent">{{ customBaseInfo.integrity * 100 || 0 }}%</p>
              <p class="intention">资料完整度</p>
            </div>
            <div class="info-right" v-else>
              <p class="precent">{{ customBaseInfo.clickCount || 0 }}</p>
              <p class="intention">访问次数</p>
            </div>
          </div>
        </div>
      </div>
      <div class="tab-container van-hairline--bottom">
        <van-tabs
          v-show="isTab"
          v-model="activeIndex"
          color="#007AE6"
          :line-width="20"
          title-active-color="#007AE6"
          title-inactive-color="#9BA4B4"
          sticky
          animated
          :ellipsis="false"
          @click="tabToggle"
        >
          <van-tab
            v-for="item in tabList"
            :key="item.index"
            :title="item.label"
          ></van-tab>
        </van-tabs>
      </div>
      <div class="tab-box">
        <div class="tab-item" v-if="activeIndex === 0">
          <custom-detail-info-edit
            :customerInfo="customBaseInfo"
            :clientId="clientId"
          />
        </div>
        <div class="tab-item" v-if="activeIndex === 1">
          <ul class="follow">
            <li class="follow-item van-hairline--bottom">
              <p class="sub-title">客户来源</p>
              <p class="show-txt ellipsis">{{customBaseInfo.source == 1 ? "名片浏览" : customBaseInfo.source == 2 ? "楼盘浏览：" : customBaseInfo.source == 3 ? "文章浏览：" : "系统分配"}}{{customBaseInfo.source == 1 ? "" : customBaseInfo.linkerSource}}</p>

              <div class="relation" @scroll="scrollHandle" :class="{ 'right-blank' : showAll, 'left-blank' : isScroll }">
                <div class="relation-item">
                  <div class="circle">
                    <img :src="relationFirst.headImg">
                  </div>
                  <p class="name" style="color:#13284D">我</p>
                </div>
                <p class="external-dashed" v-if="!relationList.length"></p>
                <div class="relation-item item-width" v-if="relationList.length">
                  <p class="line-dashed"></p>
                  <div class="circle" v-for="(item, index) in (!showAll ? relationList.slice(0, 4) : relationList )" 
                   :class="{ 'm-l-24': index, 'scroll-image' : showAll, 'last-child': index === relationList.length - 1 }">
                    <img :src="item.headImg" :style="{ zIndex: index+1 }" />
                    <p class="ellipsis name" v-if="showAll">{{ item.name }}</p>
                  </div>
                  <p class="dynamic-text" v-show="!showAll">{{ relationText }}</p>
                </div>
                <div class="relation-item">
                  <img :src="relationLast.headImg" class="last-img" />
                  <p class="ellipsis name" style="color:#445166" >{{ relationLast.name }}</p>
                </div>
              </div>
              <p class="show-or-hide" v-if="relationList.length > 4">
                <span v-show="!showAll" @click="showAll = true">展开<van-icon name="arrow" /></span>
                <span v-show="showAll"  @click="showAll = false; isScroll = false;"><van-icon name="arrow-left" />收起</span>
              </p>
            </li>
            <li class="follow-item" style="padding-bottom: 0px;" v-if="analysisListData.length">
              <div class="title-txt">
                <span class="sub-title">关注楼盘</span>
                <span class="more" @click="jump" :style="{ visibility: analysisListData.length <= 3 ? 'hidden' : 'visible'}">
                  所有楼盘<i class="iconfont icon-jiantou"></i></span>
              </div>
              <div class="house-list" >
                <custom-detail-house-list
                  :itemInfo="v"
                  v-for="(v,k) in analysisListData"
                  v-if="k <= 2"
                  :key="k"
                ></custom-detail-house-list>
              </div>
            </li>
          </ul>
          <div class="track-list">
            <van-list
              v-model="trackLoading"
              :finished="trackFinished"
              @load="onLoad"
            >
              <custom-detail-track :trackList="trackList" :finished="trackFinished" />
            </van-list>
          </div>
          <!-- <custom-detail-analyze v-if="!showActionBar"
            :lineChartHidden="lineChartHidden"
            :lineData="lineData"
          /> -->
        </div>
      </div>
      <div class="bottom van-hairline--top">
        <thread v-if="showActionBar" 
        :clientMobile="clientMobile"
        @oncustomer="customerHandler"
        @onphone="phoneHandler"
        @onconsult="consultHandler"
        />
        <custom-operation v-else
          :clientMobile="clientMobile"
          @onreport="reportHandler"
          @onphone="phoneHandler"
          @onconsult="consultHandler"
        />
      </div>
    </div>
  </div>
</template>
<script>
import * as types from '@/store/mutation-types'
import CustomDetailAnalyze from 'COMP/Custom/CustomDetailAnalyze'
import CustomDetailTrack from 'COMP/Custom/CustomDetailTrack'
import CustomDetailInfoEdit from 'COMP/Custom/CustomDetailInfoEdit'
import CustomDetailHouseList from 'COMP/Custom/CustomDetailHouseList'
import CustomOperation from 'COMP/Custom/CustomOperation'
import Thread from 'COMP/Custom/thread'
import CustomService from 'SERVICE/customService'
import commonService from 'SERVICE/commonService'
import dynamicsService from 'SERVICE/dynamicsService'
import { ImagePreview } from 'vant'
import { fullArea } from '@/utils/fullArea'
import Clipboard from 'clipboard'
import { mapGetters } from 'vuex'
import strFormat from '@/filters/strFormat'
import { scrollTo } from '@/utils/scrollTo'
import Avatar from '@/components/Avatar'

export default {
  components: {
    CustomDetailAnalyze,
    CustomDetailTrack,
    CustomOperation,
    Thread,
    Avatar,
    CustomDetailInfoEdit,
    CustomDetailHouseList
  },
  data: () => ({
    activeIndex: 0,
    tabList: [
      { label: "资料与意向", index: 0 },
      { label: "来源与足迹", index: 1 }
    ],
    showAll: false,
    isTab: true,
    clientId: '',
    clientMobile: '',
    showActionBar: '',
    loading: false,
    finished: false,
    isScroll: false,
    current: 1,
    size: 10,
    analysisListData: [],// 关注楼盘列表
    customBaseInfo: null, // 客户详情
    lineChartHidden: false,//七日活跃
    lineData: [],
    trackCurrent: 1,
    trackLoading: false,
    trackFinished: false,
    trackList: [],
    thread: '', // 访客进来标识
    isSetCustomer: '', // 置为客户标识
    threadStatus: 0, // 客户状态
    activityTrack: '', // 动态进来标识
    from: {}, // 来源路由信息
    windowResize: false, // 监听窗口变化
  }),
  beforeRouteEnter (to, from, next) {
    next(vm => vm.from = from)
  },
  created () {
    this.getQueryParams()
  },
  mounted () {
    this.resize()
  },
  computed:{
    ...mapGetters(['userInfo']),
    relationFirst() {
      if (this.customBaseInfo) {
        return this.customBaseInfo.relationList[0]
      }
      return []
    },
    relationLast() {
      if (this.customBaseInfo) {
        let relationList = this.customBaseInfo.relationList
        return relationList[relationList.length - 1]
      }
      return []
    },
    relationList() {
      if (this.customBaseInfo) {
        let relationList = this.customBaseInfo.relationList
        return relationList.slice(1, -1)
      }
      return []
    },
    relationText() {
      let relationList = this.relationList
      if (relationList && relationList.length) {
        let text = relationList.length >= 3 ? relationList.map(item => item.name).slice(0, 2).join('、') + `等${relationList.length}人` : relationList.map(item => item.name).join('、')
        return text
      }
      return ''
    }
  },
  methods: {
    scrollHandle () {
      if (this.showAll) {
        this.isScroll = true
      }
    },
    /**
     * 获取查询参数
     */
    getQueryParams () {
      try {
        let { activityTrack, thread, unreadDynamicCount  } =  this.$route.query
        this.clientId = this.$route.params.id
        if (thread) { // 访客进来
          this.isTab = false
          this.activeIndex = 1
          this.showActionBar = true
          document.title = "访客详情"
        }
        if (Number(unreadDynamicCount) ) {
          this.getUpdateTime(this.clientId)
        }
        if (activityTrack) { // 动态进来
          this.activityTrack = activityTrack
          this.trackScroll()
        }
        this.getCustomerInfo(this.clientId)
        this.getCustomerBuildingAnalysisList()
        /**
         * 七日趋势图暂时隐藏取消
         */
        // this.getCustomerSevenDayTrendChart(this.clientId)
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 获取字符长度
     */
    getLen (str) {
      return strFormat.getLen(str)
    },

    /**
     * 监听软键盘
     */
    resize () {
      let height = document.body.clientHeight
      window.onresize = () => {
        if (height - document.body.clientHeight > 30) {
          this.windowResize = true
        } else {
          this.windowResize = false
        }
      }
    },

    /**
     * 切换tab
     */
    tabToggle (index) {
      this.activeIndex = index
      this.finished = false
    },

    /**
     * 预览头像
     */
    previewAvatarUrl () {
      if (this.customBaseInfo.clientAvatarUrl != '') {
        this.instance = ImagePreview({
          images: [this.customBaseInfo.clientAvatarUrl],
          startPosition: 0
        })
      }
    },

    /**
     * 复制到黏贴板
     */
    copy () {
      new Clipboard('.copy')
      this.$toast('复制成功')
    },

    /**
     * 关注楼盘列表
     */
    async getCustomerBuildingAnalysisList () {
      try {
        const result = await CustomService.getCustomerBuildingAnalysisList(this.clientId, 1, 10)
        this.analysisListData = result.records
        this.loading = false
        this.finished = true
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 查看所有楼盘
     */
    jump () {
      this.$router.push({ name: 'custom-follow-house', query: { clientId: this.clientId } })
    },

    /**
     * 客户详情-资料
     */
    async getCustomerInfo (id) {
      try {
        const result = await CustomService.getCustomerInfo(id)
        this.customBaseInfo = { 
          ...result, 
          remarkName: result.remarkName || result.wxChatNickName, 
          relationList: result.relationList.reverse(), 
          positionCode: this.parseAddress(result.intentionArea || this.$store.state.user.userArea.city)
        }
        this.clientMobile = result.phone ? result.areaCode + " " + result.phone : ""
        // 访客0 意向客户2
        this.activeIndex = result.clientStrangerFlag == 2 ? 0 : 1
        this.isTab = result.clientStrangerFlag == 2
        this.showActionBar = result.clientStrangerFlag !== 2

        // console.log(result.clientStrangerFlag)
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 解析地址
     */
    parseAddress (address) {
      try {
        let code = ''
        if (address) { // 存在意向区域
          if (address.indexOf('/') !== -1 || address.indexOf('-') !== -1) {
            let position = address.split(address.indexOf('/') !== -1 ? '/' : '-')
            for (const key in fullArea.county_list) {
              if (fullArea.county_list[key] === position[position.length - 1]) {
                code = key
                break
              }
            }
          } else { // 默认定位
            for (const key in fullArea.city_list) {
              if (fullArea.city_list[key] === address) {
                code = key
                break
              }
            }
          }
        }
        return code
      } catch (error) {
        console.log(error)
      }
    },
    dynamicFontSize(item) {
      let name = item.remarkName || item.clientName
      let fontSize = name.length >= 12 ? 'name-18' : 'name-24' ;
      return  fontSize
    },
    /**
     * 更新客户资料信息
     */
    async updateCustomerInfo (params) {
      try {
        await CustomService.updateCustomerInfo(params)
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 足迹定位
     */
    trackScroll () {
      this.getCustomerSevenDayTrendChart(this.clientId)
    },

    /**
     * 客户足迹
     */
    async onLoad () {
      try {
        const res = await CustomService.getCustomerDynamicList(this.clientId, this.trackCurrent)
        if (this.trackCurrent === 1) {
          this.trackList = res.records
          // if (this.$route.query.activityTrack) {
          //   this.$nextTick(() => {
          //     let element = document.querySelector('.custom-box')
          //     scrollTo(document.querySelector('.track-list').offsetTop - 10, 200, element)
          //   })
          // }
        } else {
          this.trackList = this.trackList.concat(res.records)
        }
        if (this.trackCurrent >= res.pages) {
          this.trackFinished = true
        } else {
          this.trackCurrent++
        }
        this.trackLoading = false
      } catch (e) {
        console.log(e)
      }
    },

    /**
     * 7天趋势图
     */
    async getCustomerSevenDayTrendChart (id) {
      try {
        const result = await CustomService.getCustomerSevenDayTrendChart(id)
        this.lineChartHidden = result.display == 'hide' ? true : false
        if (this.lineChartHidden == false) {
          let lineData = []
          let times = []
          let counts = []
          for (let i = 0, len = result.vo.length; i < len; i++) {
            let item = {}
            item.time = Number(result.vo[i].day)
            item.count = result.vo[i].total
            item.a = '1'
            lineData.push(item)
          }
          this.lineData = lineData
        }
      } catch (e) {
        console.log(e)
      }
    },

    /**
     * 更新未读动态
     */
    async getUpdateTime (clientId) {
      try {
        let { activityTrack, type } = this.$route.query
        await dynamicsService.updateDynamicUnreadCountVo({ sourceType: 0, clientId })
        // if (activityTrack) {
          let obj = JSON.parse(sessionStorage.getItem('listInfo'))
          obj.listInfo.find(item => {
            if (item.clientId === clientId) {
              obj.unreadCount = obj.unreadCount - item.unreadDynamicCount
              item.unreadDynamicCount = 0
              return true
            }
          })
          // [clickIndex] = { ...obj.list[clickIndex], unreadDynamicCount: 0 }
          // console.log(obj.list[clickIndex])
          sessionStorage.setItem('listInfo', JSON.stringify(obj))
        // }
      } catch (e) {
        console.log(e)
      }
    },

    /**
     * 报备
     */
    reportHandler () {
      let _reportAddInfo = {
        clientId: this.clientId,
        clientName: this.customBaseInfo.remarkName || this.customBaseInfo.clientName,
        clientPhone: this.customBaseInfo.phone,
        distributorId: this.customBaseInfo.distributorId,
        institutionId: this.customBaseInfo.institutionId,
        areaCode: this.customBaseInfo.areaCode,
        clientRemarkName: this.customBaseInfo.remarkName,
        linkerName:"",
      }
      this.$store.commit(types.REPORT_INFO, _reportAddInfo)
      this.$router.push('/user/myReport/addReport?from=custom')
    },

    /**
     * 电话
     */
    phoneHandler () {
      this.datacpReport()
      window.location.href = 'tel:' + this.clientMobile
    },
    /**
     * 电话埋点上报
     */
    async datacpReport() {
      await commonService.datacpReport({
        userActionCode:"CPDDH",
        action: "",
        agentId: this.userInfo.agentId,
        clientId: this.clientId,
        clientName: this.customBaseInfo.clientName,
        enterpriseId: this.userInfo.enterpriseId,
        userActionType:"intention",
        entranceType: 0,
        sources: "qywx"
      })
    },
    /**
     * 聊天
     */
    consultHandler () {
      this.$router.push({
        name: "message",
        query: {
          clientId: this.clientId
        }
      })
    },
    /**
     * 置为客向客户
     */
    customerHandler() {
      this.$dialog.confirm({
        title: '确定将该访客置为意向客户？',
        confirmButtonText: '确定',
        confirmButtonColor: "#EA4D2E",
        cancelButtonText: '取消',
        cancelButtonColor: "#007AE6"
      }).then(async () => {
        await this.updateCustomerInfo({ clientId: this.clientId, clientStrangerFlag: 2 })
        window.sessionStorage.removeItem("listInfo")
        this.$router.go(-1)
      }).catch((error) => { 
        console.log(error) 
      })
    }
  },
  beforeRouteLeave (to, from, next) {
    this.instance && this.instance.close()
    next()
  }
}
</script>
<style lang="less" scoped>

.van-tag--medium {
  font-size: 10px;
  margin-left: 10px;
  border: 1px solid #fff;
  padding: 0 4px;
}

.tab-container {
  /deep/ .van-tab {
    font-weight: bold;
  }
}

.custom-detail {
  background: #fff;
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100%;
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .bottom {
    height: 60px;
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
    background: #fff;
  }
  .custom-box {
    height: 100%;
    overflow-y: scroll;
    .custom-info-box {
      display: flex;
      width: 100%;
      height: 152px;
      align-items: center;
      padding: 40px 16px;
      font-size: 12px;
      font-family: PingFangSC-Semibold;
      font-weight: 300;
      color: #fff;
      background: #405170;
      .info-box {
        flex: 1;
        padding-left: 12px;
        .title {
          height: 32px;
          line-height: 32px;
          font-size: 18px;
          font-weight: bold;
          width: 260px;
        }
        .name-18 {
          font-size: 18px;
        }
        .name-24 {
          font-size: 24px;
        }
        .info-box-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          opacity: 0.8;
          .info-left {
            p {
              margin-top: 4px;
              line-height: 16px;
            }
            .nick {
              display: inline-flex;
              align-items: center;
              white-space: nowrap;
            }
          }
          .info-right {
            color: #9BA4B4;
            text-align: center;
            .precent {
              font-size: 20px;
              // font-family: DINCondensed-Bold;
              font-weight: bold;
            }
            .intention {
              // font-family: PingFangSC;
              font-weight: 400;
              height: 16px;
              line-height: 16px;
              padding-top: 2px;
            }
          }
        }
      }
    }
    .tab-box {
      flex: 1;
      padding-bottom: 60px;
      .follow {
        font-size: 12px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(156, 165, 181, 1);
        .follow-item {
          padding: 20px 16px;
          padding-bottom: 12px;
          .sub-title {
            font-size: 20px;
            font-family: PingFangSC-Semibold;
            font-weight: 600;
            color: #13284D;
          }
          .show-txt {
            margin-top: 7px;
          }
          .show-or-hide {
            // padding-top: 6px;
            text-align: center;
            color: #007AE6;
            i {
              vertical-align: top;
            }
          }
          .right-blank {
            margin-right: -16px;
            &::-webkit-scrollbar {
              display:none;
            }
          }
          .left-blank {
            margin-left: -16px;
          }
          .relation {
            // display: flex;
            // justify-content: space-between;
            position: relative;
            margin-top: 24px;
            overflow-y: scroll;
            height: 75px;
            white-space: nowrap;
            .item-width {
              min-width: calc(100% - 96px);
              .last-child {
                margin-right: 11px;
              }
            }
            .relation-item {
              z-index: 1;
              text-align: center;
              display: inline-block;
              position: relative;
              vertical-align: top;
              .circle {
                width: 48px;
                display: inline-block;
                position: relative;
              }
              .m-l-24 {
                margin-left: -24px;
              }
              .scroll-image {
                margin-left: 11px;
              }
              .dynamic-text {
                width: 100%;
                margin-top: 5px;
                margin-right: -20px;
              }
              img {
                width: 48px;
                height: 48px;
                border-radius: 50%;
                border: 2px solid rgba(0, 122, 230, 1);
              }
              .last-img {
                border: 2px solid rgba(234, 77, 46, 1);
              }
              .name {
                width: 48px;
                margin-top: 4px;
              }
            }
            .external-dashed {
              margin: 0.64rem 0.10667rem 0 0;
              width: calc(100% - 104px);
              display: inline-block;
              border-top: 0.05333rem dashed #007ae6;
            }
            .line-dashed {
              border-top: 2px dashed #007ae6;
              height: 2px;
              flex: 1;
              margin: 24px 4px 0 0px;
              position: absolute;
              top: 0;
              width: 100%;
            }
          }
          .title-txt {
            display: flex;
            justify-content: space-between;
            .more {
              font-size: 14px;
              font-family: PingFangSC-Regular;
              font-weight: 400;
              color: #969ea8;
              .i {
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
